<?php
namespace app\common\model;
use app\common\traits\Models;
use think\Model;
use think\facade\{
    App,Request,Config
};
class Attachment extends Model
{
    use Models;
    protected $readonly = [];
    protected $auto     = [];
    protected $insert   = ['ip'];
    protected $update   = [];

    //设置Ip
    protected function setIpAttr()
    {
        return Request::ip(1);
    }

    //上传图片
    public function upimg($drive='local'){
        $file = Request::file('file');
        if($file->check(['size'=>20*1024*1024,'ext'=>'jpg,jpeg,png,gif'])){
            //验证宽高比
            $image  = \think\Image::open(Request::file('file'));
            $width  = $image->width();
            $height = $image->height();
            if($width/$height > 1920/400){
                $this->error = '宽高比不能大于: 1920/400';
                return false;
            }
            $ip = Request::ip(1);
            $dir = './uploads/'.date('Y').'/'.date('m').'/'.date('d').'/';
            $filename = $dir.com_token($ip).".".$image->type();
            if (!is_dir(dirname($filename))) {
                mkdir(dirname($filename), 0755, true);
            }
            $image->thumb(1920, 1920)->save($filename);
            $url = "/".$filename;
            $this::save(['url'=>$url]);
            return $url;
        }
    }
}
